package com.framework.loippi.controller.api;

import com.framework.loippi.api.core.GenericAPIController;
import com.framework.loippi.service.PaymentService;
import org.springframework.stereotype.Controller;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Controller - 支付处理类
 *
 * @author wcj
 * @version 2.0
 */
@Controller("paymentAPIController")
public class PaymentAPIController extends GenericAPIController {


    @Resource
    private PaymentService paymentService;


    /**
     * type 充值类型  m1-一个月，m3-3个月，m6-6个月,y1-1年
     * payType 1-支付宝，2-微信
     * isApp 1-安卓APP支付,2-IOS内购
     * 会员充值
     */
	/*@RequestMapping(value = "/api/payment/userRecharge", method = RequestMethod.POST)
	public  @ResponseBody String userRecharge(Integer isApp,Integer payType, String type,HttpServletRequest request, ModelMap model) {
		APIPrincipal principal = (APIPrincipal) request.getSession().getAttribute(APIPrincipal.PREFIX_USER_SESSION);
		if(null == principal){
			return ApiUtils.error("10001","登录失效,请重新登录");
		}
		Long userId = principal.getId();
		List<LiveMemberCombo> list = liveMemberComboService.findAll();
		LiveMemberCombo combo = list.get(0);
		BigDecimal money = new BigDecimal("0.00");
		String iosKey = "";
		if("m1".equalsIgnoreCase(type)){
			//一个月
			money = combo.getOneMonth();
			iosKey = combo.getOneMonthIOSKey();
		}else if("m3".equalsIgnoreCase(type)){
			money = combo.getThreeMonth();
			iosKey = combo.getThreeMonthIOSKey();
		}else if("m6".equalsIgnoreCase(type)){
			money = combo.getSixMonth();
			iosKey = combo.getSixMonthIOSKey();
		}else if("y1".equalsIgnoreCase(type)){
			money = combo.getOneYear();
			iosKey = combo.getOneYearIOSKey();
		}else{
			return ApiUtils.error("请选择充值套餐");
		}
		//money = new BigDecimal("0.01");
		String orderSn = generateBn(userId);
		String notifyUrl = "/api/payCallBack/userRecharge/"+userId+"/"+combo.getId()+"/"+orderSn+"/"+type+"/"+payType+".json";
		//安卓app支付
		if(null != isApp && isApp == 1){
			PayCommon payCommon = new PayCommon();
			payCommon.setBody("会员充值");
			payCommon.setNotifyUrl(notifyUrl);
			payCommon.setOutTradeNo(orderSn);
			payCommon.setPayAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP));
			payCommon.setTitle("会员充值");
			String pay = "";
			if(payType == 1){
				pay = AlipayMobilePay.toPay(payCommon);
			}else{
				pay = WechatMobilePay.toPay(payCommon);
			}
			return ApiUtils.success(pay);
		}
		//IOS内购支付
		if(null != isApp && isApp == 2){
			Map<String, Object> map = new HashMap<>();
			map.put("key", iosKey);
			map.put("money", money);
			return ApiUtils.success(map);
		}
		//网页扫码支付
		if(payType == 1){
			//支付宝扫码支付
			PayParameter payParameter = new PayParameter();
			payParameter.setBody("会员充值");
			payParameter.setOutTradeNo(orderSn);
			payParameter.setSubject("会员充值");
			payParameter.setTotalAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP)+"");
			String payCodeUrl = ALiPayPlugin.getPayCodeUrl(payParameter,notifyUrl);
			return ApiUtils.success(payCodeUrl);
		}else {
			//微信扫码
			String orderBody = "会员充值";
			String dealId = orderSn;
			BigDecimal totalFee = new BigDecimal("0.01");
			String payCodeUrl = WXPayPluginService.getPayCodeUrl(orderBody, dealId, orderSn, totalFee,notifyUrl);
			return ApiUtils.success(payCodeUrl);
		}
	}*/
    /**
     * 会员金币充值-----安卓/web
     * goldNum 金币数量
     * payType 1-支付宝，2-微信
     *
     */
	/*@RequestMapping(value = "/api/payment/userGoldRecharge", method = RequestMethod.POST)
	public  @ResponseBody String userGoldRecharge(Integer isApp,Integer payType, Integer goldNum,HttpServletRequest request, ModelMap model) {
		APIPrincipal principal = (APIPrincipal) request.getSession().getAttribute(APIPrincipal.PREFIX_USER_SESSION);
		if(null == principal){
			return ApiUtils.error("10001","登录失效,请重新登录");
		}
		Long userId = principal.getId();
		List<LiveGoldCombo> list = liveGoldComboService.findAll();
		LiveGoldCombo combo = list.get(0);
		BigDecimal money = new BigDecimal("0.00");
		if(goldNum == 10){
			money = combo.getTen();
		}else if(goldNum == 50){
			money = combo.getFifty();
		}else if(goldNum == 100){
			money = combo.getOneHundred();
		}else if(goldNum == 300){
			money = combo.getThreeHundred();
		}else if(goldNum == 500){
			money = combo.getFiveHundred();
		}else if(goldNum == 800){
			money = combo.getEightHundred();
		}else if(goldNum == 1000){
			money = combo.getOneThousand();
		}else if(goldNum == 1500){
			money = combo.getOneThousandFiveHundred();
		}else if(goldNum == 2000){
			money = combo.getTwoThousand();
		}else if(goldNum == 5000){
			money = combo.getFiveThousand();
		}else{
			return ApiUtils.error("请选择充值套餐");
		}
		//money = new BigDecimal("0.01");
		String orderSn = generateBn(userId);
		String notifyUrl = "/api/payCallBack/userGoldRecharge/"+orderSn+"/"+userId+"/"+goldNum+"/"+payType+".json";
		//app支付
		if(null != isApp && isApp == 1){
			PayCommon payCommon = new PayCommon();
			payCommon.setBody("会员充值");
			payCommon.setNotifyUrl(notifyUrl);
			payCommon.setOutTradeNo(orderSn);
			payCommon.setPayAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP));
			payCommon.setTitle("会员充值");
			String pay = "";
			if(payType == 1){
				pay = AlipayMobilePay.toPay(payCommon);
			}else{
				pay = WechatMobilePay.toPay(payCommon);
			}
			return ApiUtils.success(pay);
		}
		if(payType == 1){
			//支付宝
			PayParameter payParameter = new PayParameter();
			payParameter.setBody("会员金币充值");
			payParameter.setOutTradeNo(orderSn);
			payParameter.setSubject("会员金币充值");
			payParameter.setTotalAmount(money.setScale(2, BigDecimal.ROUND_HALF_UP)+"");
			String payCodeUrl = ALiPayPlugin.getPayCodeUrl(payParameter,notifyUrl);
			return ApiUtils.success(payCodeUrl);
		}else {
			//微信
			String orderBody = "会员金币充值";
			String dealId = orderSn;
			BigDecimal totalFee = new BigDecimal("0.01");
			String payCodeUrl = WXPayPluginService.getPayCodeUrl(orderBody, dealId, orderSn, totalFee,notifyUrl);
			return ApiUtils.success(payCodeUrl);
		}
	}*/

    /**
     * 会员金币充值-----ios内购
     *
     * typeId
     * 金币类型: 1-6元、2-12元、3-30元、4-45元、5-98元、
     *	6-198元、7-298元、8-498元、9-998元、10-1998元
     *
     */
	/*@RequestMapping(value = "/api/payment/ios/userGoldRecharge", method = RequestMethod.POST)
	public  @ResponseBody String userGoldRechargeIOS(Integer typeId,HttpServletRequest request, ModelMap model) {
		APIPrincipal principal = (APIPrincipal) request.getSession().getAttribute(APIPrincipal.PREFIX_USER_SESSION);
		if(null == principal){
			return ApiUtils.error("10001","登录失效,请重新登录");
		}
		Long userId = principal.getId();
		List<LiveIosGoldCombo> list = liveIosGoldComboService.findAll();
		LiveIosGoldCombo goldCombo = list.get(0);
		String key = "";
		BigDecimal money = new BigDecimal("0.00");
		Long goldNum = 0L;
		if(typeId == 1){
			key = goldCombo.getSixKey();
			money = new BigDecimal("6.00");
			goldNum = goldCombo.getSix();
		}else if(typeId == 2){
			key = goldCombo.getTwelveKey();
			money = new BigDecimal("12.00");
			goldNum = goldCombo.getTwelve();
		}else if(typeId == 3){
			key = goldCombo.getThirtyKey();
			money = new BigDecimal("30.00");
			goldNum = goldCombo.getThirty();
		}else if(typeId == 4){
			key = goldCombo.getFortyFiveKey();
			money = new BigDecimal("45.00");
			goldNum = goldCombo.getFortyFive();
		}else if(typeId == 5){
			key = goldCombo.getNinetyEightKey();
			money = new BigDecimal("98.00");
			goldNum = goldCombo.getNinetyEight();
		}else if(typeId == 6){
			key = goldCombo.getOneHundredNinetyEightKey();
			money = new BigDecimal("198.00");
			goldNum = goldCombo.getOneHundredNinetyEight();
		}else if(typeId == 7){
			key = goldCombo.getTwoHundredNinetyEightKey();
			money = new BigDecimal("298.00");
			goldNum = goldCombo.getTwoHundredNinetyEight();
		}else if(typeId == 8){
			key = goldCombo.getFourHundredEightyEightKey();
			money = new BigDecimal("498.00");
			goldNum = goldCombo.getFourHundredEightyEight();
		}else if(typeId == 9){
			key = goldCombo.getNineHundredNinetyEightKey();
			money = new BigDecimal("998.00");
			goldNum = goldCombo.getNineHundredNinetyEight();
		}else if(typeId == 10){
			key = goldCombo.getOneThousandNineHundredNinetyEightKey();
			money = new BigDecimal("1998.00");
			goldNum = goldCombo.getOneThousandNineHundredNinetyEight();
		}
		Map<String, Object> map = new HashMap<>();
		map.put("key", key);
		map.put("money", money);
		map.put("goldNum", goldNum);
		return ApiUtils.success(map);
		
	}
	*/


    /**
     * Long giftsId礼物id
     * Integer num 礼物数量
     * Long liveId直播间id
     * 礼物赠送
     */
	/*@RequestMapping(value = "/api/payment/userGivingGifts", method = RequestMethod.POST)
	public  @ResponseBody String userGivingGifts(Long liveId,Long giftId,Long num, HttpServletRequest request, ModelMap model) {
		APIPrincipal principal = (APIPrincipal) request.getSession().getAttribute(APIPrincipal.PREFIX_USER_SESSION);
		if(null == principal){
			return ApiUtils.error("10001","登录失效,请重新登录");
		}
		if(null == num || num <= 0){
			return ApiUtils.error("请选择赠送数量");
		}
		LiveUser liveUser = liveUserService.find(principal.getId());
		LiveGift liveGift = liveGiftService.find(giftId);
		Long money = liveGift.getGiftPrice() * num;
		if(liveUser.getGold() < money.intValue()){
			return ApiUtils.error("10002","对不起，您的金币不足");
		}
		LiveGiftOrder order = new LiveGiftOrder();
		order.setCreateTime(new Date());
		order.setGiftGold(money);
		order.setGiftId(giftId);
		order.setGiftName(liveGift.getGiftName());
		order.setLiveChannel(liveId);
		order.setNickName(liveUser.getNickName());
		order.setOrderNumber(generateBn(liveUser.getId()));
		order.setPayType(1);
		order.setPhone(liveUser.getPhone());
		order.setUserId(liveUser.getId());
		liveGiftOrderService.save(order);
		Integer gold  = liveUser.getGold() - money.intValue();
		liveUser.setGold(gold);
		liveUserService.update(liveUser);
		//累计直播间礼物收入数量
		LiveRoom liveRoom = liveRoomService.find(liveId);
		Long count = num;
		if(null != liveRoom.getGiftCount() && liveRoom.getGiftCount() > 0){
			count = liveRoom.getGiftCount() + num;
		}
		if(null != liveRoom.getGiftMoneyCount() && liveRoom.getGiftMoneyCount() > 0){
			liveRoom.setGiftMoneyCount(liveRoom.getGiftMoneyCount() + money);
		}else{
			liveRoom.setGiftMoneyCount(money);
		}
		liveRoom.setGiftCount(count);
		liveRoomService.update(liveRoom);
		//记录流水
		Payment payment = new Payment();
		payment.setAccount(liveUser.getPhone());
		payment.setAmount(new BigDecimal(money));
		payment.setCreateDate(new Date());
		payment.setPayDate(new Date());
		payment.setSn(generateBn(liveUser.getId()));
		payment.setStatus(1);
		payment.setPayee(liveUser.getNickName());
		payment.setPaymentPluginId("金币支付");
		payment.setPaymentPluginName("金币支付");
		'收入状态(1-收入， 0 - 支出)',
		payment.setGainStatus(1);
		//业务类型(1-会员购买，2-金币充值,3-礼物打赏)
		payment.setBizType(3);
		paymentService.save(payment);
		
		Map map = Paramap.create(); 
		//type 1正常发言  2礼物 3直播状态 4付费状态 5评论状态
		map.put("type", 2);
		//map.put("content", liveUser.getNickName()+"赠送了"+liveGift.getGiftName()+" X"+num);
		map.put("content", liveGift.getGiftName()+" X"+num);
		map.put("nickName", liveUser.getNickName());
		map.put("userType", liveUser.getUserType());
		map.put("userId", liveUser.getId());
		map.put("avatar", liveUser.getAvatar());
		map.put("giftName", liveGift.getGiftName());
		map.put("giftImage", liveGift.getGiftIcon());
		//向群发消息
		TXCloudUtils.sendGroupMsg(liveRoom.getRoomGroupId(), LiveConstants.LIVE_USER_prefix+liveUser.getId(), map);
		return ApiUtils.success();
		
	}
	*/

    /**
     * 用户消费记录
     */
	/*@RequestMapping(value = "/api/payment/userConsumptionLog", method = RequestMethod.POST)
	public  @ResponseBody String userConsumptionLog(Integer pageNumber, Integer pageSize,HttpServletRequest request, ModelMap model) {
		APIPrincipal principal = (APIPrincipal) request.getSession().getAttribute(APIPrincipal.PREFIX_USER_SESSION);
		if(null == principal){
			return ApiUtils.error("10001","登录失效,请重新登录");
		}
		Pageable pageable = new Pageable(pageNumber, pageSize);
		pageable.setOrderDirection(Direction.DESC);
		pageable.setOrderProperty("CREATE_DATE");
		Map<String, Object> parameter = new HashMap<>();
		parameter.put("account", principal.getAccount());
		pageable.setParameter(parameter);
		Page<Payment> page = paymentService.findByPage(pageable);
		Map<String, Object> data = new HashMap<>();
		data.put("dataList", page.getContent());
		data.put("pageNumber", pageNumber);
		data.put("total", page.getTotal());
		data.put("totalPages", page.getTotalPages());
		return ApiUtils.success(data);
	}*/

    //订单号
    public static String generateBn(Long userId) {
        return new SimpleDateFormat("yyMMddHHmmss").format(new Date()) + userId;
    }
}
